package com.coolcode.filter;

import com.alibaba.fastjson.JSONObject;
import com.coolcode.entity.UserInfo;
import com.coolcode.entity.LoginUserInfo;
import com.coolcode.enums.ExceptionErrorCode;
import com.coolcode.exception.ValidationException;
import com.coolcode.util.JWTUtil;
import com.coolcode.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request,response);
            return;
        }

        // 解析token
        UserInfo userInfo = JWTUtil.parseToken(token);

        // 从redis中获取用户信息
        JSONObject jsonObject = redisUtils.get(userInfo.getUserName());
        LoginUserInfo loginUserInfo = jsonObject.toJavaObject(LoginUserInfo.class);

        if (Objects.isNull(loginUserInfo)) {
            throw new ValidationException(ExceptionErrorCode.LOGIN_FAIL, "用户未登陆");
        }
        // 存入SecurityContextHolder 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUserInfo,null,loginUserInfo.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request,response);
    }
}
